﻿using DevExpress.ClipboardSource.SpreadsheetML;
using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinForm_Mes.Common;
using WinForm_Mes.Common.Models.WarehouseArea;
using static WinForm_Mes.WarehouseManagement.WarehouseForm;
namespace WinForm_Mes.WarehouseManagement
{
    public partial class WarehouseAreaForm : DevExpress.XtraEditors.XtraForm
    {
        // 创建一个静态只读的HttpClient实例，用于API请求
        private static readonly HttpClient client = new HttpClient();
        private int currentPage = 1;
        private int totalPages = 1;
        public WarehouseAreaForm()
        {
            InitializeComponent();
            bindingNavigator1.BindingSource = bindingSource1;
        }
       

        
        
        

        private async void simpleButton2_Click(object sender, EventArgs e)
        {
            using (var loading = new LoadingForm())
            {
                loading.Show(); // 显示加载窗体（播放视频）
                var newOrderNumber = await Task.Run(()=> LoadWarehouseCode()); // 获取新库号
                var warehouseList = await Task.Run(() => LoadWarehouseList()); // 加载数据

                WarehouseAreaAddForm warehouseAreaAddForm = new WarehouseAreaAddForm(newOrderNumber,warehouseList);
                warehouseAreaAddForm.StartPosition = FormStartPosition.CenterParent;
                warehouseAreaAddForm.WarehouseAdded += RefreshWarehouseList;
                loading.Close(); // 关闭加载窗体
                warehouseAreaAddForm.ShowDialog(this);
            }

            

        }
        private async Task<string> LoadWarehouseCode() 
        {
            // 1. 请求后端获取新库号
            string apiUrl = "http://localhost:5113/api/WarehouseArea/GetWarehouseAreaCode";
            string newOrderNumber = "";

            HttpResponseMessage response = await client.GetAsync(apiUrl);
            response.EnsureSuccessStatusCode();
            string responseContent = await response.Content.ReadAsStringAsync();
            newOrderNumber = responseContent;
            return newOrderNumber;
        }
        private async Task<List<ComboBoxItemWarehouseArea>> LoadWarehouseList() 
        {
            //请求后端获取仓库下拉框数据
            string ComboBoxUrl = "http://localhost:5113/api/WarehouseArea/ComboBoxWarehouse";
            HttpResponseMessage res = await client.GetAsync(ComboBoxUrl);
            res.EnsureSuccessStatusCode();
            string result = await res.Content.ReadAsStringAsync();
            ApiResult apiResult = Newtonsoft.Json.JsonConvert.DeserializeObject<ApiResult>(result);
            return apiResult.data;
        }
        // 刷新方法
        private void RefreshWarehouseList()
        {
            // 重新加载数据
            LoadWarehouseData(Convert.ToInt32(toolStripComboBox1.Text));
        }
        private async Task LoadWarehouseData(int pageSize)
        {
            var dto = new WarehouseAreaDto
            {
                WarehouseAreaCode = textEdit1.Text,
                WarehouseAreaName = textEdit2.Text,
                Index = currentPage,
                Size = pageSize
            };
            var apiPaging = await GetWarehouseAreaListAsync(dto);
            gridControl1.DataSource = apiPaging.Items;
            gridControl1.RefreshDataSource();
            totalPages = (int)Math.Ceiling((double)apiPaging.Total / apiPaging.PageSize);

            // 更新按钮状态
            UpdateNavigatorButtonStatus();
        }
        private async Task<ApiPaging<WarehouseAreaShowModel>> GetWarehouseAreaListAsync(WarehouseAreaDto dto)
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    // 参数编码，防止特殊字符和中文出错
                    string url = $"http://localhost:5113/api/WarehouseArea/GetAllWarehouseArea" +
                                 $"?WarehouseAreaCode={Uri.EscapeDataString(dto.WarehouseAreaCode ?? string.Empty)}" +
                                 $"&WarehouseAreaName={Uri.EscapeDataString(dto.WarehouseAreaName ?? string.Empty)}" +
                                 $"&Index={dto.Index}&Size={dto.Size}";

                    var response = await client.GetAsync(url);
                    if (response.IsSuccessStatusCode)
                    {
                        ApiPaging<WarehouseAreaShowModel> result = await response.Content.ReadFromJsonAsync<ApiPaging<WarehouseAreaShowModel>>();
                        bindingSource1.DataSource = result.Items;
                        gridControl1.DataSource = result.Items;
                        toolStripLabel1.Text = $"{result.Total} 条数据";
                        int totalPages = (int)Math.Ceiling((double)result.Total / result.PageSize);
                        bindingNavigatorCountItem.Text = $"第 {result.PageIndex} 页 / 共 {totalPages} 页";
                        return result;
                    }
                    else
                    {
                        MessageBox.Show("接口调用失败：" + response.StatusCode);
                        return new ApiPaging<WarehouseAreaShowModel> { Items = new List<WarehouseAreaShowModel>() };
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("接口调用异常：" + ex.Message);
                return new ApiPaging<WarehouseAreaShowModel> { Items = new List<WarehouseAreaShowModel>() };
            }
        }
        private void UpdateNavigatorButtonStatus()
        {
            // 当前页为第一页，上一页和首页按钮不可用
            bindingNavigatorMoveFirstItem.Enabled = currentPage > 1;
            bindingNavigatorMovePreviousItem.Enabled = currentPage > 1;

            // 当前页为最后一页，下一页和末页按钮不可用
            bindingNavigatorMoveNextItem.Enabled = currentPage < totalPages;
            bindingNavigatorMoveLastItem.Enabled = currentPage < totalPages;
        }

        private async void WarehouseAreaForm_Load(object sender, EventArgs e)
        {
            toolStripComboBox1.Items.Clear();
            toolStripComboBox1.Items.AddRange(new object[] { 5, 10, 20, 50, 100 });
            if (toolStripComboBox1.Items.Count > 2)
            {
                toolStripComboBox1.SelectedIndex = 2; // 默认选中20
            }
            else if (toolStripComboBox1.Items.Count > 0)
            {
                toolStripComboBox1.SelectedIndex = 0; // 至少选中第一项
            }
            toolStripComboBox1.SelectedIndexChanged += ToolStripComboBox1_SelectedIndexChanged;

            // 初次加载数据
            LoadWarehouseData(20);
        }
        private async void ToolStripComboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (int.TryParse(toolStripComboBox1.SelectedItem.ToString(), out int pageSize))
            {
                await LoadWarehouseData(pageSize);
            }
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            var dto = new WarehouseAreaDto
            {
                WarehouseAreaCode = textEdit1.Text,
                WarehouseAreaName = textEdit2.Text,
                Index = currentPage,
                Size = Convert.ToInt32(toolStripComboBox1.Text) // 默认每页20条数据
            };
            GetWarehouseAreaListAsync(dto);
        }

        private async void bindingNavigatorMoveFirstItem_Click_1(object sender, EventArgs e)
        {
            currentPage = 1;
            await LoadWarehouseData(Convert.ToInt32(toolStripComboBox1.Text));
        }

        private async void bindingNavigatorMovePreviousItem_Click(object sender, EventArgs e)
        {
            if (currentPage > 1)
            {
                currentPage--;
                await LoadWarehouseData(Convert.ToInt32(toolStripComboBox1.Text));
            }
        }

        private async void bindingNavigatorMoveNextItem_Click_1(object sender, EventArgs e)
        {
            if (currentPage < totalPages)
            {
                currentPage++;
                await LoadWarehouseData(Convert.ToInt32(toolStripComboBox1.Text));
            }
        }

        private async void bindingNavigatorMoveLastItem_Click_1(object sender, EventArgs e)
        {
            currentPage = totalPages;
            await LoadWarehouseData(Convert.ToInt32(toolStripComboBox1.Text));
        }
    }


}